import {
  setUserinfo,
  getUserinfo,
  getChannel,
  setToken,
} from "@/utils/common.js";
import { userBindMobile } from "@/api/login/index.js";

export function bindPhone(data) {
  return new Promise(function (resolve, reject) {
    // var channel = getChannel();
    userBindMobile({
      ...data,
    //   loginChannel: channel.loginChannel, // 登录渠道
    //   authType: channel.authType, // 授权渠道
    })
      .then((res) => {
        if (res && res.data) {
          setToken(res.data.token);
          resolve(res);
        } else {
          reject(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function wxBindPhone(e, block = () => {}) {
  console.log("-------e--------", e);
  if (e.detail.errMsg.indexOf("user deny") > -1) {
    uni.showModal({
      title: "提示",
      showCancel: false,
      content: "未授权不能完成该操作",
      success: function (res) {},
    });
  } else {
    console.log("用户同意", e.detail);
    var detail = e.detail;
    // 低版本没有 detail.code
    if (detail && (detail.code || detail.encryptedData)) {
      wxLogin().then((result) => {
        console.log("绑定手机之后微信登录成功", result);
        var channel = getChannel();
        userBindMobile({
          encryptedData: detail.encryptedData,
          iv: detail.iv,
          code: result.code,
          mobileCode: detail.code,
          authType: "WX",
          loginChannel: channel.loginChannel, // 登录渠道
        })
          .then((res) => {
            console.log("------绑定手机接口：-------", res);
            if (res.data) {
              setToken(res.data.token);
              block();
            } else {
              uni.showToast({
                title: "绑定手机号失败",
                icon: "none",
              });
            }
          })
          .catch((err) => {
            uni.showToast({
              title: detail.errMsg || "获取手机号code失败",
              icon: "none",
            });
          });
      });
    } else {
      uni.showModal({
        title: "提示",
        showCancel: false,
        content: "获取手机信息失败",
        success: function (res) {},
      });
    }
  }
}
function wxLogin() {
  return new Promise(function (resolve, reject) {
    uni.login({
      success: (res) => {
        console.log("-----wxLogin success-----", res);
        if (!res.code) {
          uni.hideLoading();
          uni.showModal({
            content: res.errMsg,
            showCancel: false,
          });
        }

        resolve(res);
      },

      fail(e) {
        console.log("-----wxLogin fail-----", e);
        uni.hideLoading();
        uni.showModal({
          content: "登录失败",
          showCancel: false,
        });
        reject();
      },
    });
  });
}
